<?php

	/* SVN FILE: $Id: transact.php 8 2011-03-13 08:32:38Z michele.andreoletti@gmail.com $ */
	
	/**
	 * Project Name : arcadia
	 *
	 * @author $Author: michele.andreoletti@gmail.com $
	 * @version $Revision: 8 $
	 * @lastrevision $Date: 2011-03-13 08:32:38 +0000 (Sun, 13 Mar 2011) $
	 * @filesource $URL: http://arcadia.googlecode.com/svn/trunk/include/transact.php $
	 */

	if (!isset($sAPP) || !is_string($sAPP) || !isset($aSUITE) || !is_array($aSUITE) || !isset($aSUITE[$sAPP])) {

	   	/**
		 * Intercetto la situazione in cui viene eseguito direttamente questo script (ovvero quando
		 * questo script non e' incluso in $sapp/index.php
		 *
		 */

		header('Location: ../index.php?sMsg=app-not-defined');
		die();
	} 
	
	$sScript = fnCurrentScript();
	$sSCRIPT_ROOT_PATH = (fnIsScriptInRoot() ? '.' : '..'); // Variabile utilizzata in template.php
	
	fnGetValueFromPOST();
	
	fnViewConst($sViewItemLink);

	$sBacklink = fnHtmlBacklinkFull('get', 'index.php', $bSEARCH_FORM_SHOW, $bTagsShow);

	if (!isset($iTab) || !isset($aTabsLabels[$iTab])) {
		$iTab =  $iTabDefault;
	}
	
	fnFieldsDataTypeArray($aForms[$iTab]['sFormTable']);

	if (isset($iView) && !empty($iView))
		$iAccessLvl = fnViewAccessLvl($iView, $aTABLE, $aTABLE_SECURITY_CHECK);
	else
		$iAccessLvl = fnGetAccessLvl();
		
	if (is_allowed('edit', $iAccessLvl)) {
			
		switch ($sAction) {

			case "insert":
				
				/**
				 * Prima di eseguire la query viene verificato che ci siano (e siano non vuoti) tutti i campi
				 * obbligatori (definiti in $aForms[$iTab]['aFormFieldsMandatory']).
				 */
				 
				$bMandatorySatisfied = true; 
				if (isset($aForms[$iTab]['aFormFieldsMandatory']) && !empty($aForms[$iTab]['aFormFieldsMandatory'])) {
					foreach ($aForms[$iTab]['aFormFieldsMandatory'] as $sField) {
						if (fnCheckFieldsDataType($sField, 'date')) {
							if (!isset($sField) || $$sField == '0000-00-00') ($bMandatorySatisfied ? false : $bMandatorySatisfied);
						} else {	
							if (!isset($sField) || empty($$sField)) $bMandatorySatisfied = ($bMandatorySatisfied ? false : $bMandatorySatisfied);
						}
					}
				}
		
				$sFields = '';
				$sValues = '';
				foreach ($aForms[$iTab]['aFormFields'] as $sField) {
					// la query contiene solo i campi per cui l'utente ha i privilegi di modifica
					if (is_allowed('edit', fnFieldAccessLvl($iAccessLvl, $iTab, $sField))) { 
						$sFields .= "`$sField`, ";
						$sValue = (isset($$sField) ? $$sField : '');
						$sValue = (fnCheckFieldsDataType($sField, 'numeric') ? (isset($$sField) ? float($$sField) : 0) : $sValue);
						$sValue = (fnCheckFieldsDataType($sField, 'checkbox') ? (isset($$sField) ? $$sField : 0) : $sValue);
						$sValue = (fnCheckFieldsDataType($sField, 'date') ? (!empty($$sField) ? date_convert($$sField, 'sql') : '0000-00-00') : $sValue);
						$sValue = ($sField == 'id' ? "NULL" : "\"$sValue\"");
						$sValues .= $sValue.", ";
					}
				}
				
				$sQuery = "INSERT INTO `".$aForms[$iTab]['sFormTable']."` (".substr($sFields, 0, -2).", `tsLastModify`) VALUES (".substr($sValues, 0, -2).", CURRENT_TIMESTAMP())"; 
				$rResult = custom_mysql_query($sQuery);
				$iView = mysql_insert_id($rConn);

				if ( isset($aForms[$iTab]['sFormFieldsAutoIncrement']) && !empty($aForms[$iTab]['sFormFieldsAutoIncrement']) ) {
					$sQuery ="UPDATE `".$aForms[$iTab]['sFormTable']."` SET `".$aForms[$iTab]['sFormFieldsAutoIncrement']."` = '$iView' WHERE `id` = '$iView'";
					$rResult = custom_mysql_query($sQuery);
				}
				
				$sRedirect = "./$sViewItemLink?iView=$iView&sMsg=new-record";				
				fnUpdateLog('NEW RECORD', $iView, $sViewSelectFrom, 'I');				
			
				if ($sAPP == 'visioni') {
					
					/**
					 * TODO:
					 * Eseguire una ricerca di visioni "irregolari" relative al fornitore oppure al reparto,
					 * in modo da avvisare chi sta inserendo una nuova prova visione nel caso ci siano
					 * dei precedenti irregolari
					 *
					 */
				
				}
				break;	
		
		
		
			case "update":

				$bError = fnCheckView ($iView, $sViewSelectFrom, $sViewSelectGroupBy, 'bError');
				
				if ($bError == false) {
					$sUpdates = '';
					foreach ($aForms[$iTab]['aFormFields'] as $sField) {
						// la query contiene solo i campi per cui l'utente ha i privilegi di modifica
						if (is_allowed('edit', fnFieldAccessLvl($iAccessLvl, $iTab, $sField))) {
							if ($sField != 'id')  {
								$sValue = (isset($$sField) ? $$sField : '');
								$sValue = (fnCheckFieldsDataType($sField, 'numeric') ? (isset($$sField) ? float($$sField) : 0) : $sValue);
								$sValue = (fnCheckFieldsDataType($sField, 'checkbox') ? (isset($$sField) ? $$sField : 0) : $sValue);
								$sValue = (fnCheckFieldsDataType($sField, 'date') ? (!empty($$sField) ? date_convert($$sField, 'sql') : '0000-00-00') : $sValue);
								$sUpdates .= "`$sField` = \"$sValue\", ";
							}
						}
					}
					
					$sQuery = "UPDATE `".$aForms[$iTab]['sFormTable']."` SET ".$sUpdates." `tsLastModify` = CURRENT_TIMESTAMP() WHERE `id` = '".$iView."'";
					$rResult = custom_mysql_query($sQuery);
					$sRedirect = "./$sViewItemLink?iView=$iView&iTab=$iTab&sMsg=record-edited";
					fnUpdateLog('RECORD EDITED', $iView, $sViewSelectFrom);
					
				} else {
					$sRedirect = "./$sViewItemLink?iView=$iView&iTab=$iTab&sMsg=record-not-found";
					fnUpdateLog('RECORD NOT FOUND', $iView, $sViewSelectFrom, 'E');
				
				} 
			
				break;	
			
			
			
			case "trash-verify":
			case "purge-verify":
				
				$sAccessLvl = ($sAction == 'trash-verify' ? 'delete' : 'sysop');
				
				if (is_allowed($sAccessLvl, $iAccessLvl)) {
					
					$aData = fnCheckView ($iView, $sViewSelectFrom, $sViewSelectGroupBy, 'aData');
					
					if (!empty($aData)) {
					
						$sTableTitle = "Conferma Eliminazione".($sAction == "purge-verify" ? " Definitiva" : '');
						$SHeaderTitle = $sAPP_NAME." &raquo; ".$sTableTitle;
						/* HTML */
						$sLEFT_NAV_IMG = ($sAction == "purge-verify" ? "important.png" : "user-trash-full.png");
						$html .= "<div class=\"ui-state-highlight ui-corner-all\" style=\"margin-top: 20px; margin-right: 30%; margin-bottom: 20px;\">
									<p align='center'>
									Sei sicuro di voler <strong>eliminare</strong>".($sAction == "purge-verify" ? "&nbsp;<strong>definitivamente</strong>" : "")." la seguente scheda?
									</p><p align='center'>";
									$iRow = 1;
									foreach ($aVIEW[$sViewItemLink]['aDelVerifyText'] as $aRow) {
										if ($iRow == 1) { // LA PRIMA RIGA E' VISUALIZZATA IN GRASSETTO
											$html .= "<strong>";
										}
										$i = 0;
										foreach ($aRow as $sField) {
											if (0 < $i && $i < sizeof($aRow) && !empty($aData[$sField])) {
												$html .= " &raquo; ";
											}
											$html .= $aData[$sField];
											$i++;
										}
										if ($iRow == 1) {
											$html .= "</strong>";
										}
										$html .= "<br/>";
										$iRow++;
									}
						$html .= "	</p><div style='clear: left;'></div>
								  </div>";
						
						/* CONFERMA */
						$html .= "<form name='delete' class='buttons' method='post' action='transact.php'>";
						$html .= "<input type='hidden' name='iView' value='".$iView."'>";
						$html .= "<input type='hidden' name='sViewItemLink' value='".$sViewItemLink."'>";
						$html .= "<input type='hidden' name='sAction' value='".($sAction == "trash-verify" ? "trash-confirmed" : "purge-confirmed")."'>";
						if ($sAction == "trash-verify") {
							$html .= "<div style=\"margin-top: 20px; margin-right: 30%; margin-bottom: 20px;\">
										<label for='sTrashWhy' style='font-size: 120%;'>Motivo eliminazione scheda (opzionale)</label>
										<textarea style='width: 100%; height:4.5em;' name='sTrashWhy'></textarea>
									</div>"; }
						$html .= "<input type='submit' value='Elimina' style='margin-top: 6px;'>";		
						$html .= "</form>"; 
						
						/* ANNULLA */
						$html .= "<form name='view' class='buttons' method='get' action='$sViewItemLink'>";
						$html .= "<input type='hidden' name='iView' value='$iView'>";
						$html .= "<input type='hidden' name='sAction' value='view'>";
						$html .= "<input type='submit' value='Annulla' style='margin-top: 6px;'>";	
						$html .= "</form></div>";
						$sHeadContent = "<script type='text/javascript' charset='utf-8'>
											$().ready(function() {
												$('button, input:submit', '.buttons').button();
											});
										</script>
										<style type='text/css'>
											body { background: #fff; }
										 	.layout-grid td.normal { background: #fff; }
										</style> ";
						
						$sRedirect = '';
						$bSEARCH_FORM_SHOW = false;
						require_once("$sSCRIPT_ROOT_PATH/themes/$sTHEME/template.php");
						die();
						
					} else {
						$sRedirect = $sBacklink.($sBacklink == 'index.php' ? '?' : '&').'sMsg=record-not-found';
						fnUpdateLog('RECORD NOT FOUND', $iView, $sViewSelectFrom, 'E');
					}
					
				} else {
					$sRedirect = "./$sViewItemLink?iView=$iView&sMsg=low-rights";
					fnUpdateLog('LOW RIGHTS', $iView, $sViewSelectFrom, 'S');

				}

				break;
	
	
	
			case "trash-confirmed":
				
				if (is_allowed('delete', $iAccessLvl)) {
					
					$aData = fnCheckView ($iView, $sViewSelectFrom, $sViewSelectGroupBy, 'aData');
					
					if (!empty($aData)) {
						$sQuery = " UPDATE `".$aForms[$iTab]['sFormTable']."` SET `iTrash`='1', `tsTrashWhen`=CURRENT_TIMESTAMP() ".
							(!empty($sTrashWhy) ? ", `sTrashWhy`=\"".$sTrashWhy."\"" : '' )." WHERE `id` = '$iView'";
						$rResult = custom_mysql_query($sQuery);
						
						$sRedirect = $sBacklink.($sBacklink == 'index.php' ? '?' : '&').'sMsg=record-trashed';
						fnUpdateLog('RECORD TRASHED', $iView, $sViewSelectFrom, 'I');
					
						if ($sAPP == 'visioni') { // SPECIFICO PER $sAPP == 'visioni'
							// CERCO UNA SCHEDA (NON NEL CESTINO) CHE PUNTA ALLA SCHEDA CANCELLATA: CONTROLLO I CAMPI "iRinnovo" E "iViewRinnovo"
							$sQuery = "SELECT * FROM `$sViewSelectFrom` WHERE `iTrash`='0' and `iRinnovo`='1' AND `iViewRinnovo` = '".$aData['id']."' "; 
							$rResult = custom_mysql_query($sQuery);
							if (mysql_num_rows($rResult) == 1) {
								$aRow = mysql_fetch_array($rResult);
								// AGGIORNO LA SCHEDA CHE PUNTA ALLA SCHEDA CANCELLATA CON NUOVI VALORI NEI CAMPI "iRinnovo" E "iViewRinnovo"
								$sQuery = "UPDATE `".$aForms[$iTab]['sFormTable']."` SET
									`iRinnovo` = '".(empty($aData['iRinnovo']) ? 0 : 1)."', 
									`iViewRinnovo` = '".(empty($aData['iRinnovo']) ? 0 : $aData['iViewRinnovo'])."'
									WHERE `id` = '".$aRow['id']."'"; 	
								$rResult = custom_mysql_query($sQuery);
								// AGGIORNO LA SCHEDA CANCELLATA CON NUOVI VALORI NEI CAMPI "iRinnovo" E "iViewRinnovo"
								$sQuery = "UPDATE `".$aForms[$iTab]['sFormTable']."`
									SET `iRinnovo` = '0', `iViewRinnovo` = '0'
									WHERE `id` = '".$aData['id']."'"; 	
								$rResult = custom_mysql_query($sQuery);
							}
						}

					} else  {
						$sRedirect = $sBacklink.($sBacklink == 'index.php' ? '?' : '&').'sMsg=record-not-found';
						fnUpdateLog('RECORD NOT FOUND', $iView, $sViewSelectFrom, 'E');
	
					}

				} else {
					$sRedirect = "./$sViewItemLink?iView=$iView&sMsg=low-rights";
					fnUpdateLog('LOW RIGHTS', $iView, $sViewSelectFrom, 'S');
		
				}
				
				break;
	
	
	
			case "restore":
				
				if (is_allowed('delete', $iAccessLvl)) {
					
					$aData = fnCheckView ($iView, $sViewSelectFrom, $sViewSelectGroupBy, 'aData');
					
					if (!empty($aData)) {
						$sQuery = "UPDATE `".$aForms[$iTab]['sFormTable']."` SET `iTrash`='0', `tsTrashWhen`='0000-00-00 00:00:00', `sTrashWhy`='' WHERE id = '$iView'";
						$rResult = custom_mysql_query($sQuery);
						$sRedirect = "./$sViewItemLink?iView=$iView&sMsg=record-restored";
						fnUpdateLog('RECORD RESTORED', $iView, $sViewSelectFrom, 'I');
					
					} else  {
						$sRedirect = $sBacklink.($sBacklink == 'index.php' ? '?' : '&').'sMsg=record-not-found';
						fnUpdateLog('RECORD NOT FOUND', $iView, $sViewSelectFrom, 'E');

					}	
					
				} else {
					$sRedirect = "./$sViewItemLink?iView=$iView&sMsg=low-rights";
					fnUpdateLog('LOW RIGHTS', $iView, $sViewSelectFrom, 'S');
				}
			
				break;
			
			
			
			case "purge-confirmed":
				
				if (is_allowed('sysop', $iAccessLvl)) {

					$aData = fnCheckView ($iView, $sViewSelectFrom, $sViewSelectGroupBy, 'aData');
					
					if (!empty($aData)) {
						$sQuery = fnQueryDeleteFromTrash($aForms[$iTab]['sFormTable'], $sViewSelectFrom, $iView);
						$rResult = custom_mysql_query($sQuery, 'fnQueryDeleteFromTrash()');
						$sRedirect = $sBacklink.($sBacklink == 'index.php' ? '?' : '&').'sMsg=record-purged';
						fnUpdateLog('RECORD PURGED', $iView, $sViewSelectFrom, 'I');
						
						
					} else  {
						// RECORD NON TROVATO!
						$sRedirect = $sBacklink.($sBacklink == 'index.php' ? '?' : '&').'sMsg=record-not-found';
						fnUpdateLog('RECORD NOT FOUND', $iView, $sViewSelectFrom, 'E');

					}
					
				} else {
					$sRedirect = "./$sViewItemLink?iView=$iView&sMsg=low-rights";
					fnUpdateLog('LOW RIGHTS', $iView, $sViewSelectFrom, 'S');
					
				}

				break;



			default:
				$sRedirect = "./$sViewItemLink?iView=$iView&iTab=$iTab&sMsg=low-rights";
				fnUpdateLog('ACTION NOT VALID', $iView, $sViewSelectFrom, 'E');
				break;
				
		}
		
	} else {
		$sRedirect = $sBacklink.($sBacklink == 'index.php' ? '?' : '&').'sMsg=low-rights';
		fnUpdateLog('LOW RIGHTS', $iView, $sViewSelectFrom, 'S');
	
	}

	fnHtmlTransactFooter($sQuery, $sRedirect);

?><?php if (!fnShowDebugMsg())  { ?>	<html><body bgcolor="#fff"></body></html> <?php } ?>